package cn.sjx.graduate.web.controller;


import cn.sjx.graduate.domain.Employee;
import cn.sjx.graduate.domain.LeaveList;
import cn.sjx.graduate.exception.BusinessException;
import cn.sjx.graduate.qo.QueryObject;
import cn.sjx.graduate.service.ILeaveService;
import cn.sjx.graduate.service.IRedisService;
import cn.sjx.graduate.util.JsonResult;
import cn.sjx.graduate.util.TokenUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author bo-feifei
 * @since 2022-05-05
 */
@RestController
@RequestMapping("/leave")
@Api(tags = "请假相关信息接口")
public class LeaveController {

    @Autowired
    private ILeaveService leaveService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IRedisService redisService;

    @GetMapping("query")
    @ApiOperation(value = "分页查询所有请假信息")
    public JsonResult<IPage<LeaveList>> query(QueryObject qo, HttpServletRequest request) {
        String token = TokenUtil.getToken(request);
        Employee employee = redisService.getUserByToken(token);
        if (employee == null) {
            return JsonResult.error("当前未登录用户");
        }
        IPage<LeaveList> leaveListIPage = leaveService.queryPage(qo, employee);
        System.out.println("leaveListIPage = " + leaveListIPage);
        return JsonResult.success(leaveListIPage);
    }

    @PostMapping("saveOrUpdate")
    @ApiOperation(value = "添加、审核请假信息")
    public JsonResult<?> saveOrUpdate(@RequestBody LeaveList leaveList, HttpServletRequest request) {
        Long id = leaveList.getId();
        if (id == null) {
            // 添加请假信息
            String token = TokenUtil.getToken(request);
            Employee employee = redisService.getUserByToken(token);
            if (employee == null) {
                throw new BusinessException("token错误，可能是未登录");
            }
            // 获取当前请假人
            Long employeeId = employee.getId();
            leaveList.setLeaveEmployeeId(employeeId);
            leaveList.setEmployeeNickName(employee.getNickname());
            leaveList.setCheckState(0);
            leaveList.setCreateTime(new Date());
            leaveService.saveOrUpdate(leaveList);
            return JsonResult.success();
        } else {
            // 审核
            leaveService.checkLeaveApply(leaveList);
        }
        return JsonResult.success();
    }
}

